<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

use SiteService;
use App\Models\Site;

/**
 * 站点中间件
 * @package App\Http\Middleware
 */
class SiteMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $this->init();
        return $next($request);
    }

    protected function init()
    {
        $site = request('site');
        $site = is_numeric($site) ? Site::find($site) : $site;
        $site = $site ?? SiteService::getByDomain();
        if (!($site instanceof Site)) {
            abort(404, '站点不存在');
        }
        SiteService::cache($site);
    }
}
